package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

@Controller
@RequestMapping("/order")
@SessionAttributes(value={"loginAccount","order","cart","orderList"})

public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    CartService cartService;

    @GetMapping("/newOrderForm")
    public String newOrderForm(){
        return "/order/NewOrderForm";
    }

    @PostMapping("confirmOrder")
    public String confirmOrder(Order order, Model model){

        Account loginAccount = (Account)model.getAttribute("loginAccount");

        String str = getRandomString(10);
        order.setOrderId(str);
        Date Date = new Date();
        String orderDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date);
        order.setOrderDate(orderDate);

        order.setUserId(loginAccount.getUsername());
        order.setTotalPrice(loginAccount.getCart().getPrice());
        order.setisBuy("0");//表示还没有购买
        order.setDeliver("0");//表示还没有发货

        orderService.insertOrder(order);

        for(int i = 0;i < loginAccount.getCart().getCartItemList().size();i++){

            CartItem cartItem = loginAccount.getCart().getCartItemList().get(i);
            cartItem.setUsername(loginAccount.getUsername());
            cartItem.setOrderId(order.getOrderId());

            orderService.insertOrderCart(cartItem);
        }

        loginAccount.setOrder(order);
        order.setCart(loginAccount.getCart());

        model.addAttribute("loginAccount",loginAccount);
        model.addAttribute("order",order);

        return "/order/ConfirmOrder";
    }

    @GetMapping("/viewOrder")
    public String viewOrder(Model model){

        Account loginAccount = (Account)model.getAttribute("loginAccount");
        Cart cart = loginAccount.getCart();

        if(cart == null){
            model.addAttribute("error","购物车为空！");
            return "ErrorH";
        }

        loginAccount.getOrder().setisBuy("1");

        //通过产品ID去更新buyRec
        orderService.updateOrderList(loginAccount.getOrder().getOrderId(),loginAccount.getUsername());

        cartService.removeCart(loginAccount.getUsername());
        cartService.removeCartItemAll(loginAccount.getUsername());

        loginAccount.setCart(null);

        model.addAttribute("loginAccount",loginAccount);
        model.addAttribute("cart",loginAccount.getCart());

        return "/order/ViewOrder";
    }

    @GetMapping("/viewListOrder")
    public String viewListOrder(Model model){

        Account loginAccount = (Account)model.getAttribute("loginAccount");

        ArrayList<Order> orderList = orderService.searchOrder(loginAccount.getUsername());
        //为什么这里可以用session，是因为每次都是重新读数据库数据然后赋值
        model.addAttribute("orderList", orderList);

        return "/order/ListOrders";
    }

    @GetMapping("viewOrderInOrderList")
    public String viewOrderInOrderList(String orderId,Model model){

        Account loginAccount = (Account)model.getAttribute("loginAccount");

        Order order = orderService.searchOrderByorderID(orderId);
        ArrayList<CartItem> arrayListCart = orderService.searchOrderCart(orderId,loginAccount.getUsername());

        loginAccount.setOrder(order);
        model.addAttribute("arrayListCart",arrayListCart);
        model.addAttribute("loginAccount",loginAccount);

        return "/order/ViewOrderInOrderList";
    }

    @GetMapping("/buyOrder")
    private String buyOrder(String orderId,Model model){

        Account loginAccount = (Account)model.getAttribute("loginAccount");
        orderService.updateOrderList(orderId,loginAccount.getUsername());
        Order order = orderService.searchOrderByorderID(orderId);

        ArrayList<CartItem> arrayListCart = orderService.searchOrderCart(orderId,loginAccount.getUsername());
        loginAccount.setOrder(order);

        model.addAttribute("arrayListCart",arrayListCart);
        model.addAttribute("order",order);
        model.addAttribute("loginAccount",loginAccount);

        return "/order/ViewOrderInOrderList";
    }

    @GetMapping("/adminViewOrder")
    private String adminViewOrder(Model model){
        ArrayList<Order> AdminOrderList = orderService.getOrderList();

        model.addAttribute("AdminOrderList",AdminOrderList);
        return "/administrator/Order/AdminViewOrder";
    }
    @GetMapping("/AdminEditOrder")
    private String AdminEditOrder(String orderId,String username,Model model){

        Order order = orderService.searchOrderByorderID(orderId);
        ArrayList<CartItem> arrayListCart = orderService.searchOrderCart(orderId,username);

        model.addAttribute("arrayListCart",arrayListCart);
        model.addAttribute("order",order);

        return "/administrator/Order/EditOrder";
    }

    @PostMapping("/AdminUpdateOrder")
    private String AdminUpdateOrder(Order order){
        orderService.updateOrder(order);
        return "redirect:/order/adminViewOrder";
    }
    @GetMapping("/deleteOrder")
    private String deleteOrder(String orderId){
        orderService.deleteOrder(orderId);
        orderService.deleteOrderCart(orderId);
        return "redirect:/order/adminViewOrder";
    }

    @GetMapping("/confirmDeliver")
    private String confirmDeliver(String orderId,Model model){
        model.addAttribute("orderId",orderId);
        return "/administrator/Order/ConfirmDeliver";
    }

    @GetMapping("/getFastCode")
    @ResponseBody
    private String getFastCode(){
        String fastCode="";
        String str="0123456789";
        Random random=new Random();
        StringBuffer s =new StringBuffer();
        for(int i=0;i<3;i++){
            int number=random.nextInt(10);
            s.append(str.charAt(number));
        }
        fastCode = s.toString();
        fastCode +='-';

         s =new StringBuffer();
        for(int i=0;i<3;i++){
            int number=random.nextInt(10);
            s.append(str.charAt(number));
        }

        fastCode += s.toString();
        return fastCode;
    }

    @PostMapping("/OrderDeliver")
    private String OrderDeliver(String orderId,String fastmail,String fastCode,String shippingAddress){
        Order order = orderService.searchOrderByorderID(orderId);
        order.setDeliver("1");
        order.setFastmail(fastmail);
        order.setFastCode(fastCode);
        order.setShippingAddress(shippingAddress);
        orderService.updateDeliver(order);

        return "redirect:/order/adminViewOrder";
    }
    @GetMapping("/viewDeliver")
    private String viewDeliver(String orderId,Model model){
        Order order = orderService.searchOrderByorderID(orderId);

        model.addAttribute("order",order);
        return "/order/viewDeliver";
    }

    private String getRandomString(int length) {
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer s =new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            s.append(str.charAt(number));
        }
        return s.toString();
    }

}
